package com.zl.learning.io.test.com.ronsoft.books.nio.channels;

/**
 * Created by zhaolei on 2017/4/28.
 */

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOT4{

    private static void client(){
        try{
            Selector selector=Selector.open();
            InetSocketAddress isa=new InetSocketAddress("www.baidu.com",80);
            SocketChannel sc=SocketChannel.open(isa);
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_WRITE|SelectionKey.OP_READ);
            int keyn;
            while((keyn=selector.select())>0){
                Set readykey=selector.selectedKeys();
                Iterator it=readykey.iterator();
                while(it.hasNext()){
                    SelectionKey skey=(SelectionKey)it.next();
                    it.remove();
                    SocketChannel scc=(SocketChannel)skey.channel();

                    if((skey.readyOps()&SelectionKey.OP_WRITE)==SelectionKey.OP_WRITE){
                        String head="GET / HTTP/1.1/r/n" +
                                "Host: www.baidu.com/r/n" +
                                "Connection:close/r/n"+
                                "/r/n";
                        ByteBuffer bbf=ByteBuffer.wrap(head.getBytes());
                        scc.write(bbf);
                        skey.interestOps(SelectionKey.OP_READ);
                    }else if((skey.readyOps()&SelectionKey.OP_READ)==SelectionKey.OP_READ){
                        ByteBuffer bff=ByteBuffer.allocate(512);
                        String str=null;
                        byte [] byt;
                        while(true){
                            int n=scc.read(bff);
                            if(n>0){
                                bff.flip();
                                byt=new byte[bff.limit()];
                                bff.get(byt);
                                System.out.println(new String(byt));
                                bff.clear();
                            }else if(n==-1){
                                break;
                            }
                        }
                        scc.close();
                        skey.cancel();

                    }

                }
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        client();
    }
}